package service

import (
	"context"
	"errors"
	"gitee.com/yunduansing/limitsecondkill/common"
	"gitee.com/yunduansing/limitsecondkill/data"
	"gitee.com/yunduansing/limitsecondkill/model"
	"sync"
)
var mu sync.Mutex
func KillOrder(productId int) (result bool,err error) {
	cluster:=common.NewCluster()
	num,err:=cluster.Get(context.Background(),"StockNum_1").Int()
	if num==0&&err==nil{
		return false,errors.New("商品已秒杀完毕，没有多余库存。")
	}
	db,err:=common.GetDB()
	if err!=nil||db==nil{
		return
	}
	tx,err:=db.Beginx()
	if err!=nil{
		return
	}
	stockData,err:=data.FindStockByProductId(tx,productId)
	if err!=nil||len(stockData)==0{
		tx.Rollback()
		return
	}
	stock:=stockData[0]
	if stock.Num<=0{
		tx.Rollback()
		mu.Lock()
		defer mu.Unlock()
		cluster.Do(context.Background(),"Set","StockNum_1",0)
		return false,errors.New("商品已秒杀完毕，没有多余库存。")
	}
	err=data.Create(tx,model.CreateModel{
		ProductId: productId,
		Name:    stock.Name,
	})
	if err!=nil{
		tx.Rollback()
		return
	}
	err=data.SubStock(tx,productId)
	if err!=nil{
		tx.Rollback()
		return
	}
	tx.Commit()
	return true,nil
}

func SaveStockNumToRedis()  {
	cluster:=common.NewCluster()
	db,err:=common.GetDB()
	if err!=nil||db==nil{
		return
	}
	stockList,err:=data.GetStockByProductId(db,1)
	if err!=nil{
		panic(err)
	}
	if len(stockList)==0{
		panic("商品不存在")
	}
	cluster.Do(context.Background(),"Set","StockNum_1",stockList[0].Num)
	//
	//cluster.Set(context.Background(),"StockNum_1",stockList[0].Num,time.Duration())
	//_,err=(*cluster).Do("Set","StockNum_1",stockList[0].Num)
	//if err!=nil{
	//	panic(err)
	//}
}

func OrderConsumer()  {
	
}
